package cn.edu.hunau.java.week03.day05;

import java.io.*;
import java.nio.charset.Charset;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class EmpManagerService {

    public void writerEmployeeInfo(Employee emp){
        try(FileOutputStream fos=new FileOutputStream("dir/emps.text",true);
            PrintWriter pw=new PrintWriter(fos,true, Charset.forName("UTF-8"));){
            pw.println(emp);
        }catch(Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }

    private Map<Integer,Employee> emps;
    public EmpManagerService(){
        emps=new HashMap<>();
        readFileLoadData();
        System.out.println(emps.size());
    }

    public void readFileLoadData(){
        try(FileInputStream fis=new FileInputStream("dir/emps.text");
            InputStreamReader isr=new InputStreamReader(fis,"utf-8");
            BufferedReader br=new BufferedReader(isr);){
            String line=null;
            while((line=br.readLine())!=null){
                Employee emp=parseEmployee(line);
                emps.put(emp.getId(),emp);
            }
        }catch(Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }

    private Employee parseEmployee(String line){
        String[] datas=line.split(":");
        Employee emp=new Employee();
        emp.setId(Integer.parseInt(datas[0]));
        emp.setName(datas[1]);
        emp.setSalary(Double.parseDouble(datas[2]));
        emp.setJob(datas[3]);
        emp.setTelphone(datas[4]);
        emp.setIntoDate(LocalDate.parse(datas[5]));
        emp.setManagerId("null".equals(datas[6])?null:Integer.parseInt(datas[6]));
        return emp;
    }

    public Set<String> jobs(){
        Set<String> result=emps.values().stream()
                .collect(Collectors.mapping(Employee::getJob,Collectors.toSet()));
        return result;
    }

    public Integer getEmpId(){
        int max=emps.keySet().stream().max(Integer::compareTo).get();
        return max+1;
    }

    public Map<Integer, List<Employee>> manager(){
        Map<Integer,List<Employee>> manager=emps.values().stream()
                .filter(e->e.getManagerId()!=null)
                .collect(Collectors.groupingBy(Employee::getManagerId));
        return manager;
    }
}
